#!/usr/bin/env bash

set -ex

source $SNAP/actions/common/utils.sh

use_snap_env

exit_if_service_not_expected_to_start k8s-dqlite

if [ -e "${SNAP_DATA}/var/lock/low-memory-guard.lock" ]
then
	echo "not starting dqlite because of low memory guard lock"
	exit 0
fi

app=k8s-dqlite

if ! [ -e "$SNAP_DATA/args/${app}" ]
then
  exit 0
fi

# We add some delay so that systemd really retries the restarts
sleep 6

if [ ! -e "${SNAP_DATA}/var/lock/skip-aio-tune.lock" ]
then
  increase_sysctl_parameter "fs.aio-max-nr" "1048576"
fi

if [ ! -e "${SNAP_DATA}/var/lock/skip-inotify-tune.lock" ]
then
  increase_sysctl_parameter "fs.inotify.max_user_instances" "1024"
  increase_sysctl_parameter "fs.inotify.max_user_watches" "1048576"
fi

set -a
if [ -e "${SNAP_DATA}/args/${app}-env" ]
then
  . "${SNAP_DATA}/args/${app}-env"
fi
set +a

declare -a args="($(cat $SNAP_DATA/args/$app))"
exec "$SNAP/bin/$app" "${args[@]}"
